package anything.jdom;

import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.SAXBuilder;
import java.io.*;
import java.util.*;

public class XMLEdit {

  private String filename = null;
  private boolean sub_check = false;

  public XMLEdit(String confFile) {
    this.filename = confFile;
  }// end of constructor

  public boolean edit(String domain, String subdomain, String value) {

    SAXBuilder builder = new SAXBuilder();
    Element current = null;
    try {
      Document doc = builder.build(filename);
      current = doc.getRootElement();
      builder = null;
    }catch (JDOMException e) {
      System.out.println(filename + " is not well-formed.");
      System.out.println(e.getMessage());
      //System.exit(-1);
      return false;
    }catch(IOException e){
      e.printStackTrace();
      return false;
    }

    Element clean = new Element(current.getName());
    Document myDoc = new Document(clean);

    List children;
    Iterator iterator;
    children = current.getChildren();
    iterator = children.iterator();

    while(iterator.hasNext()){ // check every node
      current=(Element)iterator.next();
      Element first = new Element(current.getName());

      if(current.getName().equals("server")) {
        first.setAttribute("name", current.getAttributeValue("name"));
        // if match domain check innernode 
        if(current.getAttributeValue("name").equals(domain)) {
          this.sub_check = true;
        }
      }
      
      // if match domain check innernode 
      if(current.getName().equals(domain))
        this.sub_check = true;

      List inChildren = current.getChildren();
      Iterator inIterator = inChildren.iterator();
        
      while(inIterator.hasNext()){ // check every innernode
        current=(Element)inIterator.next();


        Element second = new Element(current.getName());
        second.setText(current.getValue());

        if(sub_check && current.getName().equals(subdomain)) {
          second.setText(value);
          sub_check = false;
        }
        first.addContent(second);
        //System.out.println("name inner = " + current.getName() + " ; value = " + current.getValue());
      } // end inner while
      clean.addContent(first);
    } // end main while

    // write file to disk
    try {
      XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
      FileWriter writer = new FileWriter(filename);
      outputter.output(myDoc, writer);
      writer.close();
    } catch (java.io.IOException e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }
  public static void main(String[] args) {
    XMLEdit xe= new XMLEdit("res/test/jdom/touchscreen_conf.xml");
    System.out.println(xe.edit("misc", "insertInform", "8"));
  }
}
